/**
 * 
 */
package com.nail.zhaogr.front.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javacommon.util.Md5Bean;

import javax.servlet.http.Cookie;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.util.WebUtils;

import cn.org.rapid_framework.web.scope.Flash;

import com.nail.zhaogr.model.Members;
import com.nail.zhaogr.service.MembersManager;
import com.nail.zhaogr.vo.query.MembersQuery;

/**
 * @author Nail
 *
 */
public class LoginAction  extends BaseAction {
	
	protected static final String LOGIN_FAIL = "/front/Members/login.jsp";
	protected static final String LOGIN_SUCESS= "!/Index/index.do";
	
	private Members members ;

	private MembersManager membersManager;
	
	private String imageCode;
	
	private boolean rememberMe;

	
	public String indexLogin() {
		return LOGIN_FAIL;
	}
	
	public String exit(){
		ServletActionContext.getRequest().getSession().removeAttribute("memberInfo");
		//WebUtils.setSessionAttribute(ServletActionContext.getRequest(), "memberInfo", null);
		Cookie[]  cookies=getRequest().getCookies();       
		Cookie cookie = new Cookie("SESSION_LOGIN_USERNAME",null); // 保存用户名到Cookie
		String host = getRequest().getServerName();
        cookie.setPath("/");
        cookie.setDomain(host);
        cookie.setMaxAge(60*60*24*30);
        getResponse().addCookie(cookie);
	      // 保存密码到Cookie，注意需要加密一下
	      cookie = new Cookie("SESSION_LOGIN_PASSWORD", null);
	      cookie.setPath("/");
	      cookie.setDomain(host);
	      cookie.setMaxAge(60*60*24*30);
	      getResponse().addCookie(cookie);
		return LOGIN_SUCESS;
	}
	
	public String login() {

		members.setPassword(Md5Bean.getInstance().getMD5ofStr(members.getPassword()));
		if (membersManager.checkLoginName(members.getLoginName())) {
			members = membersManager.login(members);
			Map map = new HashMap();
			if (members != null) {
				/*map.put("loginName", members.getLoginName());
				map.put("loginName", members.get);*/
				WebUtils.setSessionAttribute(getRequest(), "memberInfo", members);
				
				String host = getRequest().getServerName();
		        Cookie cookie = new Cookie("SESSION_LOGIN_USERNAME", members.getLoginName()); // 保存用户名到Cookie
		        cookie.setPath("/");
		        cookie.setDomain(host);
		        cookie.setMaxAge(60*60*24*30);
		        getResponse().addCookie(cookie);
		        if (rememberMe) {
		          // 保存密码到Cookie，注意需要加密一下
		          cookie = new Cookie("SESSION_LOGIN_PASSWORD", members.getPassword());
		          cookie.setPath("/");
		          cookie.setDomain(host);
		          cookie.setMaxAge(60*60*24*30);
		          getResponse().addCookie(cookie);
		        }
				return LOGIN_SUCESS;
			} else {
				addActionMessage("密码错误，请重试！");
				Flash.current().error("密码错误，请重试！");
				return LOGIN_FAIL;
			}

		} else {
			addActionMessage("用户名不存在");
			Flash.current().error("用户名不存在");
			return LOGIN_FAIL;
		}

	}
	
	public String ajaxLogin(){
		Map map = new HashMap();
		try{
			members.setPassword(Md5Bean.getInstance().getMD5ofStr(members.getPassword()));
			MembersQuery memberVo = new MembersQuery();
			
			
			map.put("memberInfo", memberVo);
			if (membersManager.checkLoginName(members.getLoginName())) {
				members = membersManager.login(members);
				
				if (members != null) {
					/*map.put("loginName", members.getLoginName());
					map.put("loginName", members.get);*/
					WebUtils.setSessionAttribute(getRequest(), "memberInfo", members);
					
					String host = getRequest().getServerName();
			        Cookie cookie = new Cookie("SESSION_LOGIN_USERNAME", members.getLoginName()); // 保存用户名到Cookie
			        cookie.setPath("/");
			        cookie.setDomain(host);
			        cookie.setMaxAge(60*60*24*30);
			        getResponse().addCookie(cookie);
			        if (rememberMe) {
			          // 保存密码到Cookie，注意需要加密一下
			          cookie = new Cookie("SESSION_LOGIN_PASSWORD", members.getPassword());
			          cookie.setPath("/");
			          cookie.setDomain(host);
			          cookie.setMaxAge(60*60*24*30);
			          getResponse().addCookie(cookie);
			        }
			        copyProperties(memberVo,members);
			        map.put("code", 1);
				} else {
					map.put("code", -1);
				}

			} else {
				//addActionMessage("用户名不存在");
				//Flash.current().error("用户名不存在");
				map.put("code", 0);
			}
			
			this.getResponse().getWriter().write(JSONObject.fromObject(map).toString());
			
			/*if (membersManager.checkLoginName(members.getLoginName())) {
				members = membersManager.login(members);
				if (members != null) {
					WebUtils.setSessionAttribute(ServletActionContext.getRequest(), "memberInfo", members);
					this.getResponse().getWriter().write("1");
				} else {
					this.getResponse().getWriter().write("-1");
				}
	
			} else {
				addActionMessage("用户名不存在");
				Flash.current().error("用户名不存在");
				this.getResponse().getWriter().write("0");
			}*/
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String checkLogin(){
		this.getResponse().setCharacterEncoding("UTF-8");
		Map map = new HashMap();
		try{
			Members memberInfo = this.getMemberInfo();
			MembersQuery memberVo = new MembersQuery();
				
			
			map.put("memberInfo", memberVo);
			if(memberInfo!=null){
				copyProperties(memberVo,memberInfo);
				map.put("code", 1);
				//this.getResponse().getWriter().write("1");
			}else{
				String usernameCookie = null;
			    String passwordCookie = null;
			    Cookie[] cookies = this.getRequest().getCookies();
			    if (cookies != null){
			      for (Cookie cookie : cookies) {
			        if ("SESSION_LOGIN_USERNAME".equals(cookie.getName())) {
			          usernameCookie = cookie.getValue(); // 得到cookie的用户名
			        }
			        if ("SESSION_LOGIN_PASSWORD".equals(cookie.getName())) {
			          passwordCookie = cookie.getValue(); // 得到cookie的密码
			        }
			      }
			      if (usernameCookie != null && passwordCookie != null) { // 如果存在
			    	  members.setLoginName(usernameCookie);
			    	  members.setPassword(passwordCookie);
			    	  if (membersManager.checkLoginName(members.getLoginName())) {
			  			members = membersManager.login(members);
			  			if (members != null) {
			  				copyProperties(memberVo,memberInfo);
			  				WebUtils.setSessionAttribute(getRequest(), "memberInfo", members);
			  				map.put("code", 1);
			  				//this.getResponse().getWriter().write("1");
						} else {
							//addActionMessage("密码错误，请重试！");
							//Flash.current().error("密码错误，请重试！");
							map.put("code", -1);
							//this.getResponse().getWriter().write("0");
						}
					} else {
						//addActionMessage("用户名不存在");
						//Flash.current().error("用户名不存在");
						map.put("code", 0);
					}
			      }
			    }else{
			    	map.put("code", 0);
			    }
			}
			
			this.getResponse().getWriter().write(JSONObject.fromObject(map).toString());
		}catch (Exception e) {
		}
		
		return null;
	}
		
	public String checkImageCode(){
		try {
			if (imageCode != null
					&& !imageCode.equalsIgnoreCase(ServletActionContext.getRequest()
							.getSession().getAttribute("imageCode")+"")) {
				ServletActionContext.getResponse().getWriter().write("验证码错误");

			} else {
				ServletActionContext.getResponse().getWriter().write("");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void setMembers(Members members) {
		this.members = members;
	}

	public void setMembersManager(MembersManager membersManager) {
		this.membersManager = membersManager;
	}

	public String getImageCode() {
		return imageCode;
	}

	public void setImageCode(String imageCode) {
		this.imageCode = imageCode;
	}

	public Members getMembers() {
		return members;
	}

	@Override
	public void prepare() throws Exception {
		members = new Members();
	}

	@Override
	public Object getModel() {
		return members;
	}

	/**
	 * @return the rememberMe
	 */
	public boolean getRememberMe() {
		return rememberMe;
	}

	/**
	 * @param rememberMe the rememberMe to set
	 */
	public void setRememberMe(boolean rememberMe) {
		this.rememberMe = rememberMe;
	}

}
